<template>
  <div id="app">
    <a-input placeholder="请输入任务" class="my_ipt" :value="inputVal" @change="handlerInputChange" />
    <a-button type="primary" @click="addItemList">添加事项</a-button>

    <a-list bordered :dataSource="showListByViewKey" class="dt_list">
      <a-list-item slot="renderItem" slot-scope="item">
        <!-- 复选框 -->
        <a-checkbox :checked="item.done" @change="(e)=>cbCheckedChange(e,item.id)">{{item.info}}</a-checkbox>
        <!-- 删除链接 -->
        <a slot="actions" @click="removeItemById(item.id)">删除</a>
      </a-list-item>

      <!-- footer区域 -->
      <div slot="footer" class="footer">
        <!-- 未完成的任务个数 -->
        <span>{{ unDoneLength }}条剩余</span>
        <!-- 操作按钮 -->
        <a-button-group>
          <template v-for="(item, index) in btnList">
            <a-button
              :key="index"
              :type="index ===viewKey?`primary`:`default`"
              @click="changeViewIndex(index)"
            >{{item}}</a-button>
          </template>
        </a-button-group>
        <!-- 把已经完成的任务清空 -->
        <a @click="cleanDone">清除已完成</a>
      </div>
    </a-list>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
export default {
  name: 'app',
  data () {
    return {
      btnList: ['全部', '未完成', '已完成']
    }
  },
  created () {
    this.$store.dispatch('getList')
  },
  computed: {
    ...mapState(['list', 'inputVal', 'viewKey']),
    ...mapGetters(['unDoneLength', 'showListByViewKey'])
  },
  methods: {
    handlerInputChange (e) {
      this.$store.commit('setInputVal', e.target.value)
    },
    // 为列表新增 item 项
    addItemList () {
      if (this.inputVal.trim().length <= 0) {
        return this.$message.warning('文本框内容不能为空')
      }
      this.$store.commit('addItem')
    },
    // 根据id删除对应的任务事项
    removeItemById (id) {
      this.$store.commit('removeItem', id)
    },
    // 切换复选框的选中状态的回调函数
    cbCheckedChange (e, id) {
      const params = {
        id: id,
        status: e.target.checked
      }
      this.$store.commit('changeItemDone', params)
    },
    // 清除已完成数据
    cleanDone () {
      this.$store.commit('cleanDone')
    },
    // 改变底部选项按钮
    changeViewIndex (index) {
      this.$store.commit('changeViewIndex', index)
    }
  }
}
</script>

<style scoped>
#app {
  padding: 10px;
  width: 700px;
  margin: 100px auto;
}

.my_ipt {
  width: 500px;
  margin-right: 10px;
}

.dt_list {
  width: 500px;
  margin-top: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
